Page({
  data: {
    inputText: '',
    isAdding: false,
    records: []
  },

  onLoad() {
    // 从本地存储加载记录
    this.loadRecords();
  },

  // 输入框内容变化
  onInputChange(e) {
    this.setData({
      inputText: e.detail.value
    });
  },

  // 点击加号开始添加
  onAddRecord() {
    if (!this.data.isAdding) {
      // 第一次点击，进入输入模式
      this.setData({
        isAdding: true
      });
      return;
    }

    // 确认添加记录
    const text = this.data.inputText.trim();
    if (!text) return;

    const newRecord = {
      id: Date.now().toString(),
      text: text,
      time: this.formatTime(new Date())
    };

    const newRecords = [newRecord, ...this.data.records];
    
    this.setData({
      records: newRecords,
      inputText: '',
      isAdding: false
    });

    // 保存到本地存储
    this.saveRecords(newRecords);
  },

  // 取消添加
  onCancelAdd() {
    this.setData({
      inputText: '',
      isAdding: false
    });
  },

  // 删除记录
  onDeleteRecord(e) {
    const id = e.currentTarget.dataset.id;
    const newRecords = this.data.records.filter(record => record.id !== id);
    
    this.setData({
      records: newRecords
    });

    // 更新本地存储
    this.saveRecords(newRecords);
  },

  // 保存记录到本地存储
  saveRecords(records) {
    try {
      wx.setStorageSync('werewolf_records', records);
    } catch (error) {
      console.error('保存记录失败:', error);
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      });
    }
  },

  // 从本地存储加载记录
  loadRecords() {
    try {
      const records = wx.getStorageSync('werewolf_records') || [];
      this.setData({ records });
    } catch (error) {
      console.error('加载记录失败:', error);
    }
  },

  // 格式化时间
  formatTime(date) {
    const hour = date.getHours().toString().padStart(2, '0');
    const minute = date.getMinutes().toString().padStart(2, '0');
    const second = date.getSeconds().toString().padStart(2, '0');
    return `${hour}:${minute}:${second}`;
  },

  // 清空所有记录
  onClearAll() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有记录吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({ records: [] });
          this.saveRecords([]);
          wx.showToast({
            title: '已清空',
            icon: 'success'
          });
        }
      }
    });
  }
});